package com.climaxi.core.data;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XML {

	public final static Document XMLfromString(String xml){
		
		Document doc = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
        	
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(xml));
	        doc = db.parse(is); 
	        
		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
		       
        return doc;
        
	}
	
	/** Returns element value
	  * @param elem element (it is XML tag)
	  * @return Element value otherwise empty String
	  */
	public final static String getElementValue( Node elem ) 
	{
	      Node child;
	      if( elem != null){
	          if (elem.hasChildNodes()){
	        	  child = elem.getFirstChild();
	        	  return child.getNodeValue();
	        	  /*
	              for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                  if( child.getNodeType() == Node.TEXT_NODE  ){
	                      return child.getNodeValue();
	                  }
	              }
	              */
	          }
	      }
	      return "";
	}
		 
	 public static String getXML(String link){	 
			String line = null;

			try {
				
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(link);

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				line = EntityUtils.toString(httpEntity);
				
			} catch (UnsupportedEncodingException e) {
				line = "<data status=\"error\"><message>Can't connect to server</message></data>";
			} catch (MalformedURLException e) {
				line = "<data status=\"error\"><message>Can't connect to server</message></data>";
			} catch (IOException e) {
				line = "<data status=\"error\"><message>Can't connect to server</message></data>";
			}

			return line;
	}
	 
	public static int numResults(Document doc){		
		Node results = doc.getDocumentElement();
		int res = -1;
		
		try{
			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
		}catch(Exception e ){
			res = -1;
		}
		
		return res;
	}
	
	/**
	   * Getting node value
	   * @param Element node
	   * @param key string
	* */
	public static String getValue(Element item, String str) 
	{  
	   NodeList n = item.getElementsByTagName(str);  
	   return getElementValue(n.item(0));
	}
	
	public static String NodeGetValue(NodeList n,int i,String s)
	{
		Element e = (Element) n.item(i);
		return getValue(e, s);
	}
	
	public static String NodeGetAttribute(NodeList n,int i,String s)
	{
		Element e = (Element) n.item(i);
		return e.getAttribute(s) ;
	}
	
	public static String getTagValue(String tag, Document doc) {
        Element intElement = (Element) doc.getElementsByTagName(tag).item(0);
        return intElement.getChildNodes().item(0).getNodeValue() ;
    }
}
